package org.myspringframework.mvc.render;

import com.google.gson.Gson;
import org.myspringframework.core.util.CollectionUtils;
import org.myspringframework.mvc.RequestProcessorChain;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Objects;

/**
 * org.myspringframework.mvc.render <br>
 * JSON 渲染器
 *
 * @author jaymin
 * @since 2021/5/22
 */
public class JsonResultRender implements ResultRender {
    private Object data;

    public JsonResultRender(Object result) {
        if (Objects.isNull(result)) {
            this.data = Collections.emptyMap();
            return;
        }
        this.data = result;
    }

    /**
     * 1. 设置响应头 <br>
     * 2. 向响应流写入经过GSON处理过的结果 <br>
     *
     * @param requestProcessorChain 请求执行链
     * @throws Exception
     */
    @Override
    public void render(RequestProcessorChain requestProcessorChain) throws Exception {
        HttpServletResponse httpServletResponse = requestProcessorChain.getHttpServletResponse();
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try (PrintWriter writer = httpServletResponse.getWriter()) {
            Gson gson = new Gson();
            String jsonResult = gson.toJson(data);
            writer.write(jsonResult);
            writer.flush();
        }
    }
}
